﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for RequestManager
/// </summary>
public static class RequestManager
{

    public static void HandleRequest(HttpApplication application)
    {
        // we do not need url rewriting in case of form post
        if (application.Context.Request.HttpMethod == "POST")
        {
            return;
        }

        // get rewrite path if available
        string rewritePath = RequestManager.GetRewritePath(application.Context.Request);

        if (String.IsNullOrEmpty(rewritePath) == false)
        {
            HttpContext.Current.RewritePath(rewritePath);
        }
    }


    /// <summary>
    /// Gets rewrite path for current request
    /// http://www.simple-talk.com/dotnet/asp.net/a-complete-url-rewriting-solution-for-asp.net-2.0/
    /// http://www.codeproject.com/KB/aspnet/urlrewriter.aspx
    /// http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx
    /// http://msdn.microsoft.com/en-us/library/ms972974.aspx
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    private static string GetRewritePath(HttpRequest request)
    {
        String path = request.Url.AbsolutePath; // +"?" + request.QueryString.ToString();

        if (request.QueryString.Count > 0)
        {
            path = path + "?" + request.QueryString.ToString();
        }

        // only execute those requests which do not have any extension :) :p
        // e.g. http://azadriasat.com/2011/12/11/taza-tareen?page=2
        var fileName = path.Substring(path.LastIndexOf('/'));
        if (fileName.IndexOf(".aspx") > 1)
        {
            return string.Empty;
        }

        // create rules for rewrite
        Dictionary<String, String> rules = new Dictionary<string, string>();
        rules.Add(@"/(\d{4})/(\d{2})/(\d{2})/([a-zA-Z\-]+)/(\d{1,5})(\?)", @"/Default.aspx?y=$1&m=$2&d=$3&mn=$4&page=$5&$6");
        rules.Add(@"/(\d{4})/(\d{2})/(\d{2})/(\d{1,5})", @"/Default.aspx?y=$1&m=$2&d=$3&page=$4");
        rules.Add(@"/(\d{4})/(\d{2})/(\d{2})/page-(\d{1,5})", @"/Default.aspx?y=$1&m=$2&d=$3&page=page-$4");
        rules.Add(@"/(\d{4})/(\d{2})/(\d{2})/([a-zA-Z\-]+)/(\d{1,5})", @"/Default.aspx?y=$1&m=$2&d=$3&mn=$4&page=$5");
        rules.Add(@"/(\d{4})/(\d{2})/(\d{2})/([a-zA-Z\-]+)(\?)", @"/Default.aspx?y=$1&m=$2&d=$3&mn=$4&$5");
        rules.Add(@"/(\d{4})/(\d{2})/(\d{2})/([a-zA-Z\-]+$)", @"/Default.aspx?y=$1&m=$2&d=$3&mn=$4");
        rules.Add(@"/(\d{4})/(\d{2})/(\d{2})/(\?)", @"/Default.aspx?y=$1&m=$2&d=$3&$4");
        rules.Add(@"/(\d{4})/(\d{2})/(\d{2})/", @"/Default.aspx?y=$1&m=$2&d=$3");
        rules.Add(@"/(\d{4})/(\d{2})/(\d{2})", @"/Default.aspx?y=$1&m=$2&d=$3");
        

        Regex regex;

        foreach (var rule in rules)
        {
            regex = new Regex(rule.Key);
            Match oMatch = regex.Match(path);

            if (oMatch.Success)
            {
                String finalUrl = regex.Replace(path, rule.Value);
                if (finalUrl.ToLower().Contains("aaj-ka-akhbar"))
                {
                    //finalUrl =finalUrl.ToLower().Replace("default.aspx", "ajkaakhbar.aspx");
                }
                var splittedUrl = finalUrl.Split(new char[] { '?' }, StringSplitOptions.RemoveEmptyEntries);
                if (splittedUrl.Length > 2)
                {
                    finalUrl = splittedUrl[0] + "?" + splittedUrl[1] + splittedUrl[2];
                }
                return finalUrl;
            }
        }

        return string.Empty;
    }

}